package com.gitee.shigen.generator.controller;

import cn.hutool.core.util.StrUtil;
import com.gitee.shigen.generator.service.GeneratorService;
import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @author shigenfu
 */
@Controller
@RequestMapping("/code/generator")
public class GeneratorController {

    @Resource
    private GeneratorService generatorService;

    /**
     * 代码生成
     *
     * @param tables      要生成的表，逗号隔开
     * @param packageName 包名，com.gitee.shigen
     * @param mainModule  模块名
     * @param author      作者
     * @param tablePrefix 表前缀，可为空
     * @param response    响应体
     * @throws IOException IO异常
     */
    @RequestMapping("/build")
    public void code(@RequestParam("tables") String tables,
        @RequestParam("packageName") String packageName,
        @RequestParam("mainModule") String mainModule,
        @RequestParam("author") String author,
        @RequestParam(value = "tablePrefix", required = false) String tablePrefix,
        HttpServletResponse response) throws IOException {
        if (StrUtil.isNotBlank(tables)) {
            byte[] data = generatorService.generatorCode(tables.split(","), packageName, mainModule, author, tablePrefix);
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"generator-code.zip\"");
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream; charset=UTF-8");
            IOUtils.write(data, response.getOutputStream());
        }
    }
}
